package com.gohi.main.wxapi.action;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;

import net.sf.json.JSONArray;

import org.apache.log4j.Logger;

import com.gohi.core.web.action.BaseAction;
import com.gohi.main.util.Utils;

import com.gohi.main.wxapi.util.AccoutUtil;
import com.gohi.main.wxapi.vo.JsApi;
import com.gohi.main.wxapi.vo.WxAccount;

/**
 * 读取微信图片的
 * @author Administrator
 *
 */
public class WxjsAction extends BaseAction {
	Logger logger = Logger.getLogger(WxjsAction.class);
	private String id;
	private String mid;
	private String url;//需要授权的URL
	public String index() throws Exception{
		//System.err.println("获取到"+mid);
		WxAccount wx =AccoutUtil.getAccountByid();
		String savePath = this.getRequest().getSession().getServletContext().getRealPath("/");
		String path =Utils.getBundelPath("upload", "uploadPath") +"\\"+ Utils.FormatDate(new Date(), "yyyyMM");
		URL url = new URL("http://file.api.weixin.qq.com/cgi-bin/media/get?access_token="+wx.getAccess_token()+"&media_id="+mid+"");  
		URLConnection con = url.openConnection();  
		InputStream input = con.getInputStream();  
		
		byte[] bs = new byte[1024 * 2];  
		int len;  
		// 输出的文件流保存图片至本地  
		String savename=path+"\\"+Utils.generID()+".jpg";
		OutputStream os = null;  
		int  i=0;
		String json=null;

		while ((len = input.read(bs)) != -1) {  
				if(i==0){
				//刚刚开始读取 判断 是否读取失败了
				if(len==47){
					 json = "false";
					break;
				}else{
					//判断目录是否存在
					File savefile = new File(savePath+savename);
					if (!savefile.getParentFile().exists())
						savefile.getParentFile().mkdirs();
					
					os = new FileOutputStream(savePath+savename);
					//System.err.println(savePath+savename);
				
					
					i=1;
					 json = savename.replace("\\", "/");
						
				}
				
			}
		
		os.write(bs, 0, len);  
		}
		if(os!=null){
			os.close(); 
		}
	 
		input.close();
		if(json==null){
			 json = "false";
		}
		this.getResponse().getWriter().write(json);
		return null;
	}
	
	/**
	 * 微信网友授权JS的
	 * @return
	 * @throws IOException 
	 */
	public String oauth() throws IOException{
		JsApi js = AccoutUtil.getJsApiByid(id, url);
		this.getRequest().setCharacterEncoding("GBK");
		this.getResponse().setContentType("application/json;charset=GBK");
		PrintWriter out = this.getResponse().getWriter();
		JSONArray json = JSONArray.fromObject(js);
		out.print(json.toString());
		out.flush();
		out.close();
		//System.err.println(json.toString());
		return null;
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getMid() {
		return mid;
	}
	public void setMid(String mid) {
		this.mid = mid;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}
	
	
	
	
}
